/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.biz.service.impl;

import cn.hutool.core.convert.Convert;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.domain.*;
import me.zhengjie.modules.biz.repository.*;
import me.zhengjie.modules.biz.service.HazardousChemicalsService;
import me.zhengjie.modules.biz.service.dto.HazardousChemicalsDto;
import me.zhengjie.modules.biz.service.dto.HazardousChemicalsQueryCriteria;
import me.zhengjie.modules.biz.service.dto.HazardousChemicalsTotalDto;
import me.zhengjie.modules.biz.service.dto.ProjectIdNameDto;
import me.zhengjie.modules.biz.service.mapstruct.HazardousChemicalsMapper;
import me.zhengjie.modules.biz.service.mapstruct.HazardousChemicalsTotalMapper;
import me.zhengjie.modules.biz.utils.BarcodeUtil;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.RoleRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.*;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.System;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Admin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-03-03
 **/
@Service
@EnableScheduling
@RequiredArgsConstructor
public class HazardousChemicalsServiceImpl implements HazardousChemicalsService {

    private final HazardousChemicalsRepository hazardousChemicalsRepository;
    private final HazardousChemicalsMapper hazardousChemicalsMapper;

    private final HazardousChemicalsChangeRecordRepository hazardousChemicalsChangeRecordRepository;
    private final LabRepository labRepository;
    private final CabinetRepository cabinetRepository;
    private final RoleRepository roleRepository;
    private final HazardousChemicalsTotalRepository hazardousChemicalsTotalRepository;
    private final ProjectRepository projectRepository;
    private final HazardousChemicalsTotalMapper hazardousChemicalsTotalMapper;
    private final MessageRepository hazardousChemicals;
    private final UserRepository userRepository;
    private final SettingsRepository settingsRepository;

    @Override
    public Map<String, Object> queryAll(HazardousChemicalsQueryCriteria criteria, Pageable pageable) {
        Specification<HazardousChemicals> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            if (criteria.getLabId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("labId"), criteria.getLabId()));
            }
//            if (criteria.getCabinetIds() != null) {
//                String[] cabinetList = criteria.getCabinetIds().split(",");
//                int[] cabinetIdList = new int[cabinetList.length];
//                for (int i = 0; i < cabinetList.length; i++) {
//                    cabinetIdList[i] = Integer.parseInt(cabinetList[i]);
//                }
//                Path<Object> path = root.get("cabinetId");
//                CriteriaBuilder.In<Object> in = criteriaBuilder.in(path);
//                for (int i = 0; i < cabinetIdList.length; i++) {
//                    in.value(cabinetIdList[i]);//存入值
//                }
//                predicates.add(criteriaBuilder.and(criteriaBuilder.and(in)));//存入条件集合里
//            }
            if (criteria.getCabinetId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("cabinetId"), criteria.getCabinetId()));
            }
            if (criteria.getCreatedAt() != null) {
                predicates.add(criteriaBuilder.between(root.get("createdAt"), criteria.getCreatedAt().get(0), criteria.getCreatedAt().get(1)));
            }
            if (criteria.getCategory() != null) {
                predicates.add(criteriaBuilder.equal(root.get("category"), criteria.getCategory()));
            }
            if (criteria.getType() == null) {
                predicates.add(criteriaBuilder.or((criteriaBuilder.equal(root.get("type").as(Integer.class), 1)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 2)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 3)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 4))));
            } else {
                predicates.add(criteriaBuilder.equal(root.get("type"), criteria.getType()));
            }
            if (criteria.getDangerClasses() != null) {
                predicates.add(criteriaBuilder.equal(root.get("dangerClasses"), criteria.getDangerClasses()));
            }
            if (criteria.getIngredientData() != null) {
                predicates.add(criteriaBuilder.like(root.get("ingredientData"), "%" + criteria.getIngredientData() + "%"));
            }

//            predicates.add(criteriaBuilder.notEqual(root.get("residue"), 0));

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        Page<HazardousChemicals> page = hazardousChemicalsRepository.findAll(specification, pageable);
        Page<HazardousChemicalsDto> dto = page.map(hazardousChemicalsMapper::toDto);
        List<HazardousChemicalsDto> resultDto = dto.getContent();
        for (HazardousChemicalsDto hazardousChemicalsDto : resultDto) {
            if (hazardousChemicalsDto.getLabId() != null) {
                Lab lab = labRepository.findById(hazardousChemicalsDto.getLabId()).orElseGet(Lab::new);
                if (lab.getId() != null) {
                    hazardousChemicalsDto.setLabName(lab.getName());
                }
            }

            if (hazardousChemicalsDto.getCabinetId() != null) {
                Cabinet cabinet = cabinetRepository.findById(hazardousChemicalsDto.getCabinetId()).orElseGet(Cabinet::new);
                if (cabinet.getId() != null) {
                    hazardousChemicalsDto.setCabinetName(cabinet.getName());
                }
            }
        }

        return PageUtil.toPage(dto);
    }

    @Override
    public List<HazardousChemicalsDto> queryAll(HazardousChemicalsQueryCriteria criteria) {
        Specification<HazardousChemicals> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            if (criteria.getCategory() != null) {
                predicates.add(criteriaBuilder.equal(root.get("category"), criteria.getCategory()));
            }
            if (criteria.getCreatedAt() != null) {
                predicates.add(criteriaBuilder.between(root.get("createdAt"), criteria.getCreatedAt().get(0), criteria.getCreatedAt().get(1)));
            }
            if (criteria.getLabId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("labId"), criteria.getLabId()));
            }
            if (criteria.getCabinetId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("cabinetId"), criteria.getCabinetId()));
            }
            if (criteria.getDangerClasses() != null) {
                predicates.add(criteriaBuilder.equal(root.get("dangerClasses"), criteria.getDangerClasses()));
            }
            if (criteria.getType() != null) {
                predicates.add(criteriaBuilder.equal(root.get("type"), criteria.getType()));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        List<HazardousChemicalsDto> hazardousChemicalsDtoList = hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.findAll(specification));
        for (HazardousChemicalsDto hazardousChemicalsDto : hazardousChemicalsDtoList) {
            Lab lab = labRepository.findById(hazardousChemicalsDto.getLabId()).orElseGet(Lab::new);
            hazardousChemicalsDto.setLabName(lab.getName());
            Cabinet cabinet = cabinetRepository.findById(hazardousChemicalsDto.getCabinetId()).orElseGet(Cabinet::new);
            hazardousChemicalsDto.setCabinetName(cabinet.getName());

        }
        return hazardousChemicalsDtoList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HazardousChemicalsDto findById(Integer id) {
        HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
        ValidationUtil.isNull(hazardousChemicals.getId(), "HazardousChemicals", "id", id);
        HazardousChemicalsDto hazardousChemicalsDto = hazardousChemicalsMapper.toDto(hazardousChemicals);

        hazardousChemicalsDto.parseInfo();

        return hazardousChemicalsDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HazardousChemicalsDto create(HazardousChemicals resources, boolean isNew) {
        List<HazardousChemicals> hazardousChemicals = new ArrayList<>();
//        if (isNew) {
//            if (resources.isQiCai()) {
//                hazardousChemicals = hazardousChemicalsRepository.findByNameAndType(resources.getName(), resources.getType());
//            } else if (resources.isHuaXueShiJi()) {
//                hazardousChemicals = hazardousChemicalsRepository.findByNameAndExpirationDateAndType(resources.getName(), resources.getExpirationDate(), resources.getType());
//            } else if (resources.isBiaoZhunWuZhi()) {
//                hazardousChemicals = hazardousChemicalsRepository.findByNameAndBatchNumberAndType(resources.getName(), resources.getBatchNumber(), resources.getType());
//            }
//
//            if (hazardousChemicals.size() > 0) {
//                resources.setName("请勿重复入库同一物质！");
//                return hazardousChemicalsMapper.toDto(resources);
//            }
//        }
        resources.setStatus(0);
        resources.setMeasureId(1);
        resources.setIsPastDue(0);
        resources.setName(resources.getName().trim());
        Float amount = resources.getAmount();

        if (resources.isQiCai()) {
            if (resources.getStorage() == 1) {
                resources.setCabinetId(-1);
            } else if (resources.getStorage() == 2) {
                resources.setCabinetId(-2);
            } else if (resources.getStorage() == 3) {
                resources.setCabinetId(-3);
            }

            resources.setLabId(0);

            for (int i = 0; i < amount; i++) {
                resources.setAmount(1f);
                resources.setId(0);
                resources.setResidue(1f);
                HazardousChemicalsDto hazardousChemicalsDto = hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.save(resources));
                HazardousChemicalsChangeRecord hazardousChemicalsChangeRecord = new HazardousChemicalsChangeRecord();
                hazardousChemicalsChangeRecord.setHcId(hazardousChemicalsDto.getId());
                hazardousChemicalsChangeRecord.setUserId(Convert.toInt(SecurityUtils.getCurrentUserId()));
                hazardousChemicalsChangeRecord.setName(resources.getName());
                hazardousChemicalsChangeRecord.setAmount(1f);
                hazardousChemicalsChangeRecord.setType(resources.getType());
                hazardousChemicalsChangeRecord.setState(HazardousChemicalsChangeRecord.STATE_INPUT);
                hazardousChemicalsChangeRecord.setOrderId(0);
                hazardousChemicalsChangeRecord.setDetailNumber(1f);
                hazardousChemicalsChangeRecordRepository.save(hazardousChemicalsChangeRecord);
                addTotal(resources);
            }
        } else if (resources.isHuaXueShiJi()) {

            for (int i = 0; i < amount; i++) {
                resources.setAmount(1f);
                resources.setId(0);
                //resources.setResidue(resources.getInputResidue());
                resources.setResidue(resources.getCapacity());
                HazardousChemicalsDto hazardousChemicalsDto = hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.save(resources));
                HazardousChemicalsChangeRecord hazardousChemicalsChangeRecord = new HazardousChemicalsChangeRecord();
                hazardousChemicalsChangeRecord.setHcId(hazardousChemicalsDto.getId());
                hazardousChemicalsChangeRecord.setUserId(Convert.toInt(SecurityUtils.getCurrentUserId()));
                hazardousChemicalsChangeRecord.setName(resources.getName());
                hazardousChemicalsChangeRecord.setAmount(resources.getAmount());
                hazardousChemicalsChangeRecord.setType(resources.getType());
                hazardousChemicalsChangeRecord.setState(HazardousChemicalsChangeRecord.STATE_INPUT);
                hazardousChemicalsChangeRecord.setOrderId(0);
                //hazardousChemicalsChangeRecord.setDetailNumber(resources.getInputResidue());
                //hazardousChemicalsChangeRecord.setGhNumber(resources.getInputResidue());
                hazardousChemicalsChangeRecord.setDetailNumber(resources.getCapacity());
                hazardousChemicalsChangeRecord.setGhNumber(resources.getCapacity());
                hazardousChemicalsChangeRecord.setIsReturn(2);//非领取记录
                hazardousChemicalsChangeRecordRepository.save(hazardousChemicalsChangeRecord);
                addTotal(resources);
            }

        } else if (resources.isBiaoZhunWuZhi()) {
            Cabinet cabinet = cabinetRepository.findById(resources.getCabinetId()).orElseGet(Cabinet::new);
            resources.setLabId(cabinet.getLabId());
            resources.setResidue(1f);
            for (int i = 0; i < amount; i++) {
                resources.setAmount(1f);
                resources.setId(0);
                if (resources.getUnit() == 1) {
                    resources.setResidue(resources.getAmount());
                } else {
                    resources.setResidue(resources.getCapacity());
                }
                HazardousChemicalsDto hazardousChemicalsDto = hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.save(resources));
                HazardousChemicalsChangeRecord hazardousChemicalsChangeRecord = new HazardousChemicalsChangeRecord();
                hazardousChemicalsChangeRecord.setHcId(hazardousChemicalsDto.getId());
                hazardousChemicalsChangeRecord.setUserId(Convert.toInt(SecurityUtils.getCurrentUserId()));
                hazardousChemicalsChangeRecord.setName(resources.getName());
                hazardousChemicalsChangeRecord.setAmount(resources.getAmount());
                hazardousChemicalsChangeRecord.setType(resources.getType());
                hazardousChemicalsChangeRecord.setState(HazardousChemicalsChangeRecord.STATE_INPUT);
                hazardousChemicalsChangeRecord.setAttenuation(resources.getAttenuation());
                hazardousChemicalsChangeRecord.setBatchNumber(resources.getBatchNumber());
                hazardousChemicalsChangeRecord.setExpirationDate(resources.getExpirationDate());
                hazardousChemicalsChangeRecord.setIngredientData(resources.getIngredientData());
                hazardousChemicalsChangeRecord.setMatrix(resources.getMatrix());
                hazardousChemicalsChangeRecord.setNumber(resources.getNumber());
                hazardousChemicalsChangeRecord.setFileUrl(resources.getFileUrl());
                hazardousChemicalsChangeRecord.setOrderId(0);
                hazardousChemicalsChangeRecord.setDetailNumber(resources.getCapacity());
                hazardousChemicalsChangeRecordRepository.save(hazardousChemicalsChangeRecord);

                addTotal(resources);
            }
        }

        return hazardousChemicalsMapper.toDto(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(HazardousChemicals resources) {
        HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(resources.getId()).orElseGet(HazardousChemicals::new);
        ValidationUtil.isNull(hazardousChemicals.getId(), "HazardousChemicals", "id", resources.getId());

//        updateTotal(resources);
//        HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameLabCabinet(hazardousChemicals.getName(),hazardousChemicals.getLabId(),hazardousChemicals.getCabinetId(),hazardousChemicals.getType(),hazardousChemicals.getCountType());
//        if (hazardousChemicals.getCountType()==1){
//            if (hazardousChemicalsTotal.getTotalNumber()-1!=0){
//                hazardousChemicalsTotal.setAmount(hazardousChemicalsTotal.getTotalNumber()-1);
//            }else {
//                hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//            }
//        }else {
//            if (hazardousChemicalsTotal.getTotalNumber()-hazardousChemicals.getAmount()!=0){
//                hazardousChemicalsTotal.setAmount(hazardousChemicalsTotal.getTotalNumber()-hazardousChemicals.getAmount());
//            }else {
//                hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//            }
//        }
        //resources.setAmount(resources.getCapacity());
        hazardousChemicals.copy(resources);
        hazardousChemicalsRepository.save(hazardousChemicals);
        if (hazardousChemicals.getType() == 2) {//如果是标准物质
            List<HazardousChemicals> hazardousChemicalsList = hazardousChemicalsRepository.findAllByNameNumber(hazardousChemicals.getName(), hazardousChemicals.getNumber(), hazardousChemicals.getBatchNumber());
            for (HazardousChemicals hazardousChemicals1 : hazardousChemicalsList) {
                hazardousChemicals1.setFileUrl(resources.getFileUrl());
                hazardousChemicalsRepository.save(hazardousChemicals1);
            }
        }

    }

    private void addTotal(HazardousChemicals resources) {
        if (resources.isQiCai()) {//器材
            HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository
                    .findByNameAndType(
                            resources.getName(),
                            resources.getType()
                    );

            if (hazardousChemicalsTotal == null) {
                HazardousChemicalsTotal hazardousChemicalsTotal1 = new HazardousChemicalsTotal();
                hazardousChemicalsTotal1.setAmount(resources.getAmount());
                hazardousChemicalsTotal1.setCountType(resources.getCountType());
                hazardousChemicalsTotal1.setUnit(resources.getUnit());
                hazardousChemicalsTotal1.setName(resources.getName());
                hazardousChemicalsTotal1.setLabId(resources.getLabId());
                hazardousChemicalsTotal1.setCabinetId(resources.getCabinetId());
                hazardousChemicalsTotal1.setType(resources.getType());
                hazardousChemicalsTotal1.setDangerClasses(resources.getDangerClasses());

                hazardousChemicalsTotal1.setTotalNumber(resources.getAmount());
                hazardousChemicalsTotal1.setGross(resources.getAmount());

                hazardousChemicalsTotal1.setCategory(resources.getCategory());
                hazardousChemicalsTotal1.setLocation(resources.getLocation());
                hazardousChemicalsTotal1.setStorage(resources.getStorage());
                hazardousChemicalsTotal1.setIsAudit(resources.getIsAudit());
                hazardousChemicalsTotal1.setIsApply(resources.getIsApply());
                hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal1);
            } else {
                hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() + resources.getAmount());
                hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getGross() + resources.getAmount());

                hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
            }
        } else if (resources.isHuaXueShiJi()) {//化学试剂
            HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository
                    .findByNameAndType(
                            resources.getName(),
                            resources.getType()
                    );

            if (hazardousChemicalsTotal == null) {
                resources.setResidue(resources.getInputResidue());

                HazardousChemicalsTotal hazardousChemicalsTotal1 = new HazardousChemicalsTotal();
                hazardousChemicalsTotal1.setAmount(resources.getResidue());
                hazardousChemicalsTotal1.setCountType(resources.getCountType());
                if (resources.getUnit() == 1) {
                    hazardousChemicalsTotal1.setUnit(2);
                } else {
                    hazardousChemicalsTotal1.setUnit(resources.getUnit());
                }
                hazardousChemicalsTotal1.setUnit(resources.getUnit());
                hazardousChemicalsTotal1.setName(resources.getName());
                hazardousChemicalsTotal1.setLabId(resources.getLabId());
                hazardousChemicalsTotal1.setCabinetId(resources.getCabinetId());
                hazardousChemicalsTotal1.setType(resources.getType());
                hazardousChemicalsTotal1.setDangerClasses(resources.getDangerClasses());
                hazardousChemicalsTotal1.setCategory(resources.getCategory());
                hazardousChemicalsTotal1.setLocation(resources.getLocation());
                hazardousChemicalsTotal1.setStorage(resources.getStorage());
                hazardousChemicalsTotal1.setGrade(resources.getGrade());
                hazardousChemicalsTotal1.setIsAudit(resources.getIsAudit());
                hazardousChemicalsTotal1.setIsApply(resources.getIsApply());
                hazardousChemicalsTotal1.setCategory(resources.getCategory());
                hazardousChemicalsTotal1.setNumber(resources.getNumber());
                hazardousChemicalsTotal1.setBatchNumber(resources.getBatchNumber());
                hazardousChemicalsTotal1.setIngredientData(resources.getIngredientData());
                hazardousChemicalsTotal1.setMatrix(resources.getMatrix());
                hazardousChemicalsTotal1.setAttenuation(resources.getAttenuation());
                hazardousChemicalsTotal1.setExpirationDate(resources.getExpirationDate());
                hazardousChemicalsTotal1.setFileUrl(resources.getFileUrl());

                hazardousChemicalsTotal1.setTotalNumber(resources.getResidue());
                hazardousChemicalsTotal1.setGross(resources.getResidue());

                hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal1);
            } else {
                resources.setResidue(resources.getInputResidue());

                hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() + resources.getResidue());
                hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getGross() + resources.getResidue());

                hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
            }
        } else {//标准物质
            HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository
                    .findByNameAndType(
                            resources.getName(),
                            resources.getType()
                    );

            if (hazardousChemicalsTotal == null) {
                HazardousChemicalsTotal hazardousChemicalsTotal1 = new HazardousChemicalsTotal();
                hazardousChemicalsTotal1.setAmount(resources.getAmount());
                hazardousChemicalsTotal1.setCountType(resources.getCountType());
                hazardousChemicalsTotal1.setUnit(resources.getUnit());
                hazardousChemicalsTotal1.setName(resources.getName());
                hazardousChemicalsTotal1.setLabId(resources.getLabId());
                hazardousChemicalsTotal1.setAttenuation(resources.getAttenuation());
                hazardousChemicalsTotal1.setNumber(resources.getNumber());
                hazardousChemicalsTotal1.setBatchNumber(resources.getBatchNumber());
                hazardousChemicalsTotal1.setMatrix(resources.getMatrix());
                hazardousChemicalsTotal1.setIsAudit(resources.getIsAudit());
                hazardousChemicalsTotal1.setIsApply(resources.getIsApply());
                hazardousChemicalsTotal1.setIngredientData(resources.getIngredientData());
                hazardousChemicalsTotal1.setExpirationDate(resources.getExpirationDate());
                hazardousChemicalsTotal1.setCabinetId(resources.getCabinetId());
                hazardousChemicalsTotal1.setType(resources.getType());
                hazardousChemicalsTotal1.setDangerClasses(1);
                if (resources.getUnit() == 1) {//支
                    hazardousChemicalsTotal1.setTotalNumber(resources.getAmount());
                    hazardousChemicalsTotal1.setGross(resources.getAmount());
                } else {//瓶
                    hazardousChemicalsTotal1.setTotalNumber(resources.getAmount() * resources.getCapacity());
                    hazardousChemicalsTotal1.setGross(resources.getAmount() * resources.getCapacity());
                }
                hazardousChemicalsTotal1.setCategory(resources.getCategory());
                hazardousChemicalsTotal1.setStorage(resources.getStorage());
                hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal1);
            } else {
                if (resources.getUnit() == 1) {//支
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() + resources.getAmount());
                    hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getGross() + resources.getAmount());
                } else {//瓶
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() + resources.getAmount() * resources.getCapacity());
                    hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getGross() + resources.getAmount() * resources.getCapacity());
                }

                hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
            }
        }
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
            HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameAndBatchNumber(hazardousChemicals.getName(), hazardousChemicals.getBatchNumber());
            if (hazardousChemicals.getCountType() == 1) {
                if (hazardousChemicals.getType() == 2 && Objects.equals(hazardousChemicals.getUnit(), "1")) {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getCapacity());
                    hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getCapacity());

                } else {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - 1);
                    hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getTotalNumber() - 1);

                }
                hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
                if (hazardousChemicalsTotal.getTotalNumber() == 0) {
                    hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
                }
            } else {
                hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getAmount());
                hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getAmount());

                hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
                if (hazardousChemicalsTotal.getTotalNumber() == 0) {
                    hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
                }
            }
            hazardousChemicalsRepository.deleteById(id);
        }
    }

    @Override
    public void exportEquipment(List<HazardousChemicalsDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (HazardousChemicalsDto hazardousChemicals : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("名称", hazardousChemicals.getName());
            String category = "";
            switch (hazardousChemicals.getCategory()) {
                case "1":
                    category = "玻璃器皿";
                    break;
                case "2":
                    category = "实验耗材";
                    break;
                case "3":
                    category = "采样工具";
                    break;
                case "4":
                    category = "仪器设备";
                    break;
            }
            map.put("类型", category);
            map.put("数量", hazardousChemicals.getAmount());
            String unit = "";
            switch (hazardousChemicals.getUnit()) {
                case 1:
                    unit = "个";
                    break;
                case 2:
                    unit = "台";
                    break;
                case 3:
                    unit = "套";
                    break;
            }
            map.put("单位", unit);
            String storage = "";
            switch (hazardousChemicals.getStorage()) {
                case 1:
                    storage = "器材室";
                    break;
                case 2:
                    storage = "备品室";
                    break;
                case 3:
                    storage = "外业仓库";
                    break;
            }
            map.put("仓库", storage);
            map.put("入库时间", hazardousChemicals.getCreatedAt());
            map.put("位置", hazardousChemicals.getLocation());
            map.put("备注", hazardousChemicals.getNote());

            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Map<String, Object> collect(HazardousChemicalsQueryCriteria criteria, Pageable pageable) {
        Specification<HazardousChemicals> specification = (Specification<HazardousChemicals>) (root, query, criteriaBuilder) -> {
            Predicate p = (Predicate) criteriaBuilder;
            return p;
        };
        Page<Object> page = hazardousChemicalsRepository.findAllByNameAmount(specification, pageable);
//        Page<HazardousChemicalsDto> dto = page.map(hazardousChemicalsMapper::toDto);
//        List<HazardousChemicalsDto> resultDto = dto.getContent();
//        for (HazardousChemicalsDto hazardousChemicalsDto:resultDto) {
//           HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findByNameAmount(hazardousChemicalsDto.getName(),hazardousChemicalsDto.getAmount());
//           hazardousChemicalsDto.setCountType(hazardousChemicals.getCountType());
//           hazardousChemicalsDto.setDangerClasses(hazardousChemicals.getDangerClasses());
//           hazardousChemicalsDto.setType(hazardousChemicals.getType());
//        }
//        return PageUtil.toPage(dto);
        return null;
    }

    @Override
    public void printBarCode(Integer id, HttpServletResponse response) {
        String msg = "h".concat(generateNumber(id));
        HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
        String name = hazardousChemicals.getName().concat("_").concat(String.valueOf(id));
        BarcodeUtil.printBarCode(msg, name, name, response);
    }

    @Override
    public Map<String, Object> applyListPage(HazardousChemicalsQueryCriteria criteria, Pageable pageable) {
        Page<HazardousChemicals> page = hazardousChemicalsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<HazardousChemicalsDto> dto = page.map(hazardousChemicalsMapper::toDto);
        List<HazardousChemicalsDto> resultDto = dto.getContent();
        for (HazardousChemicalsDto hazardousChemicalsDto : resultDto) {
            Lab lab = labRepository.findById(hazardousChemicalsDto.getLabId()).orElseGet(Lab::new);
            hazardousChemicalsDto.setLabName(lab.getName());
            Cabinet cabinet = cabinetRepository.findById(hazardousChemicalsDto.getCabinetId()).orElseGet(Cabinet::new);
            hazardousChemicalsDto.setCabinetName(cabinet.getName());
        }
        return PageUtil.toPage(dto);
    }

    @Override
    public List<HazardousChemicalsDto> applyList(Integer type) {
        ArrayList<String> hazardousChemicalsNameLists = hazardousChemicalsRepository.collectNameByType(type);
        ArrayList<HazardousChemicalsDto> hazardousChemicalsDtos = new ArrayList<>();
        int i = 1;
        for (String hazardousChemicalsName : hazardousChemicalsNameLists) {
            ArrayList<Float> amountList = hazardousChemicalsRepository.findAmount(hazardousChemicalsName);
            for (Float amount : amountList) {
                if (hazardousChemicalsRepository.findCountType(hazardousChemicalsName) == 1) {
                    HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.getByNameAmount(hazardousChemicalsName, amount);
                    HazardousChemicalsDto hazardousChemicalsDto = hazardousChemicalsMapper.toDto(hazardousChemicals);
                    System.out.println(hazardousChemicalsRepository.getCountByAmount(hazardousChemicalsName, amount));
//                    hazardousChemicalsDto.setTotalNum(hazardousChemicalsRepository.getCountByAmount(hazardousChemicalsName,amount));
                    hazardousChemicalsDtos.add(hazardousChemicalsDto);
                } else {
                    ArrayList<Float> amountListByName = hazardousChemicalsRepository.findAmount(hazardousChemicalsName);
                    float totalNum = 0;
                    for (float num : amountListByName) {
                        totalNum += num;
                    }
                    HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.getByNameAmount(hazardousChemicalsName, amount);
                    HazardousChemicalsDto hazardousChemicalsDto = hazardousChemicalsMapper.toDto(hazardousChemicals);
//                    hazardousChemicalsDto.setTotalNum(totalNum);
                    hazardousChemicalsDtos.add(hazardousChemicalsDto);
                    break;
                }
            }
        }
        for (HazardousChemicalsDto hazardousChemicalDto : hazardousChemicalsDtos) {
            hazardousChemicalDto.setIndex(String.valueOf(i).concat("_").concat(String.valueOf(type)));
//            hazardousChemicalDto.setProjectList(getProjectName(hazardousChemicalDto));
            i++;
        }
        return hazardousChemicalsDtos;
    }

    public List<HazardousChemicalsTotalDto> queryAllByRequest(Integer type) {
        List<HazardousChemicalsTotal> hazardousChemicalsTotalList = hazardousChemicalsTotalRepository.queryAllByHot(type, 0, 1000000000, SecurityUtils.getCurrentUserId());
        List<HazardousChemicalsTotalDto> hazardousChemicalsTotalDtoList = hazardousChemicalsTotalMapper.toDto(hazardousChemicalsTotalList);
        //List<HazardousChemicalsTotal> listCount = hazardousChemicalsTotalRepository.queryAllByNull(type,0,1000000000);

        for (HazardousChemicalsTotalDto hazardousChemicalsTotalDto : hazardousChemicalsTotalDtoList) {
            hazardousChemicalsTotalDto.setTotalNumber(hazardousChemicalsTotalRepository.sumTotalNum(hazardousChemicalsTotalDto.getName(), type));
            hazardousChemicalsTotalDto.setIndex(hazardousChemicalsTotalDto.getId().toString().concat("_").concat(hazardousChemicalsTotalDto.getType().toString()));
            hazardousChemicalsTotalDto.setProjectList(getProjectName(hazardousChemicalsTotalDto));
            hazardousChemicalsTotalDto.setTotalNum(hazardousChemicalsTotalDto.getTotalNumber());

            hazardousChemicalsTotalDto.setCapacity(hazardousChemicalsRepository.getCapacityByName(hazardousChemicalsTotalDto.getName()));
        }
        return hazardousChemicalsTotalDtoList;

    }

    @Override
    @Scheduled(cron = "0 0 8 * * ?")
    public void isPastDueH() {
        List<HazardousChemicals> hazardousChemicalsList = hazardousChemicalsRepository.findAll();
        String names = "";
        int count = 0;
        for (HazardousChemicals h : hazardousChemicalsList) {
            if (h.getExpirationDate() != null) {
                try {
                    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00"));
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(date);
                    long remindTime = Convert.toLong(settingsRepository.findByKey());
                    //cal.add(Calendar.MONTH, -3);
                    if (Objects.isNull(remindTime)) {
                        throw new RuntimeException("未查询到value");
                    }
                    long timestamp = cal.getTimeInMillis();
                    long timeStampR = cal.getTimeInMillis() + remindTime * 1000;
                    cal.setTime(h.getExpirationDate());
                    long timeStampH = cal.getTimeInMillis();

                    if (timestamp > timeStampH) {
                        names = names + " " + h.getName();
                        count++;
                        h.setIsPastDue(1);
                        hazardousChemicalsRepository.save(h);
                    }
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }

                if (count > 2) {
                    names += "等";
                    break;
                }
            }
        }

        if (names != "") {

            ArrayList<Integer> arrayLists = roleRepository.findUserIdsByRoleId();
            if (arrayLists != null) {
                for (Integer userId : arrayLists) {
                    User user = userRepository.findById(Convert.toLong(userId)).orElseGet(User::new);
                    ValidationUtil.isNull(user.getId(), "User", "id", userId);
                    Message message = new Message();
                    message.setType(2);
                    message.setUrl("/sellingWarehouse/index");
                    message.setMenuId(6);
                    message.setIsRead(0);
                    message.setName(names + "已经过期。");
                    message.setUserId(Convert.toInt(user.getId()));
                    hazardousChemicals.save(message);
                }
            }
        }
    }

    @Override
    public Map<String, Object> expireList(HazardousChemicalsQueryCriteria criteria, Pageable pageable) {

        Specification<HazardousChemicals> specification = (Specification<HazardousChemicals>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            if (criteria.getLabId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("labId"), criteria.getLabId()));
            }
            if (criteria.getCabinetId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("cabinetId"), criteria.getCabinetId()));
            }
            if (criteria.getExpirationDate() != null) {
                predicates.add(criteriaBuilder.equal(root.get("expirationDate"), criteria.getExpirationDate()));
            }
            if (criteria.getCategory() != null) {
                predicates.add(criteriaBuilder.equal(root.get("category"), criteria.getCategory()));
            }
            predicates.add(criteriaBuilder.equal(root.get("isPastDue"), 1));
            predicates.add(criteriaBuilder.notEqual(root.get("amount"), 0));
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        Page<HazardousChemicals> page = hazardousChemicalsRepository.findAll(specification, pageable);
        Page<HazardousChemicalsDto> dto = page.map(hazardousChemicalsMapper::toDto);
        List<HazardousChemicalsDto> resultDto = dto.getContent();
        for (HazardousChemicalsDto hazardousChemicalsDto : resultDto) {
            if (hazardousChemicalsDto.getCabinetId() != null) {
                Cabinet cabinet = cabinetRepository.findById(hazardousChemicalsDto.getCabinetId()).orElseGet(Cabinet::new);
                hazardousChemicalsDto.setCabinetName(cabinet.getName());
            }
        }
        return PageUtil.toPage(dto);

    }

//    @Override
//    public void destroyByIds(Integer[] ids) {
//        for (Integer id : ids) {
//            HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
//            if (hazardousChemicals.getType() == 1) {
//                List<Integer> changeIds = hazardousChemicalsChangeRecordRepository.findByHcId(hazardousChemicals.getId());
////                for (Integer changeId:changeIds) {
////                    hazardousChemicalsChangeRecordRepository.deleteById(changeId);
////                }
//                HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameAndBatchNumber(hazardousChemicals.getName(), hazardousChemicals.getBatchNumber());
//                if (hazardousChemicals.getCountType() == 1) {
//                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getAmount());
////                    hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getTotalNumber()-hazardousChemicals.getAmount());
//
//                    hazardousChemicalsTotal = hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
//                } else {
//                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getAmount());
////                    hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getTotalNumber()-hazardousChemicals.getAmount());
//
//                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
//                }
//                hazardousChemicalsRepository.deleteById(id);
//            } else if (hazardousChemicals.getType() == 3) {
//                List<Integer> changeIds = hazardousChemicalsChangeRecordRepository.findByHcId(hazardousChemicals.getId());
//                for (Integer changeId : changeIds) {
//                    hazardousChemicalsChangeRecordRepository.deleteById(changeId);
//                }
//                HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameAndBatchNumber(hazardousChemicals.getName(), hazardousChemicals.getBatchNumber());
//                if (hazardousChemicals.getCountType() == 1) {
//                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
//                    hazardousChemicalsTotal = hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
//                } else {
//                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
//                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
//                }
//                hazardousChemicalsRepository.deleteById(id);
//            } else {
//                List<Integer> changeIds = hazardousChemicalsChangeRecordRepository.findByHcId(hazardousChemicals.getId());
//                for (Integer changeId : changeIds) {
//                    hazardousChemicalsChangeRecordRepository.deleteById(changeId);
//                }
//                HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameBatchNumber(hazardousChemicals.getName(), hazardousChemicals.getBatchNumber());
//                if (hazardousChemicals.getCountType() == 1) {
//                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
//                    hazardousChemicalsTotal = hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
//                } else {
//                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
//                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
//                }
//                hazardousChemicalsRepository.deleteById(id);
//            }
//
//
//        }
//    }

    @Override
    public List<Map<String, Object>> queryNamesByType(int type) {
        return hazardousChemicalsRepository.findNamesByType(type);
    }

    @Override
    public List<HazardousChemicalsDto> refrigeratorHazarddousChemicalsList(Integer id) {
        List<HazardousChemicalsDto> hazardousChemicalsDtos = hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.refrigeratorList(id));
        for (HazardousChemicalsDto hazardousChemicalsDto : hazardousChemicalsDtos) {
            Lab lab = labRepository.findById(hazardousChemicalsDto.getLabId()).orElseGet(Lab::new);
            hazardousChemicalsDto.setLabName(lab.getName());
            Cabinet cabinet = cabinetRepository.findById(hazardousChemicalsDto.getCabinetId()).orElseGet(Cabinet::new);
            hazardousChemicalsDto.setCabinetName(cabinet.getName());
        }
        return hazardousChemicalsDtos;
    }

    public void exportChemicals(List<HazardousChemicalsDto> hazardousChemicalsDtoList, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (HazardousChemicalsDto hazardousChemicals : hazardousChemicalsDtoList) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("名称", hazardousChemicals.getName());
            map.put("级别", hazardousChemicals.getGrade());
            map.put("规格", hazardousChemicals.getCapacity());
            String unit = "";
            switch (hazardousChemicals.getUnit()) {
                case 1:
                    unit = "L";
                    break;
                case 2:
                    unit = "ml";
                    break;
            }
            map.put("单位", unit);
            map.put("数量", hazardousChemicals.getAmount());
            Lab lab = labRepository.findById(hazardousChemicals.getLabId()).orElseGet(Lab::new);
            map.put("实验室", lab.getName());
            Cabinet cabinet = cabinetRepository.findById(hazardousChemicals.getCabinetId()).orElseGet(Cabinet::new);
            map.put("试剂柜", cabinet.getName());
            String dangerClasses = null;
            switch (hazardousChemicals.getDangerClasses()) {
                case 1:
                    dangerClasses = "一般试剂（I）";
                    break;
                case 2:
                    dangerClasses = "有机试剂（II）";
                    break;
                case 3:
                    dangerClasses = "剧毒试剂/易致毒试剂（III）";
                    break;
            }
            map.put("危险等级", dangerClasses);
            String audit = null;
            switch (hazardousChemicals.getIsAudit()) {
                case 0:
                    audit = "否";
                    break;
                case 1:
                    audit = "是";
                    break;
            }
            map.put("是否审批", audit);
            map.put("入库时间", hazardousChemicals.getCreatedAt());
            map.put("备注", hazardousChemicals.getNote());

            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void exportMaterials(List<HazardousChemicalsDto> chemicalsDtoList, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (HazardousChemicalsDto hazardousChemicals : chemicalsDtoList) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("参数", hazardousChemicals.getName());
            map.put("类别", hazardousChemicals.getCategory());
            String unit = "";
            switch (hazardousChemicals.getUnit()) {
                case 1:
                    unit = "支";
                    break;
                case 2:
                    unit = "瓶";
                    break;
            }
            map.put("数量", hazardousChemicals.getAmount() + "(" + unit + ")");
            Cabinet cabinet = cabinetRepository.findById(hazardousChemicals.getCabinetId()).orElseGet(Cabinet::new);
            map.put("冰箱", cabinet.getName());
            map.put("入库时间", hazardousChemicals.getCreatedAt());
            map.put("备注", hazardousChemicals.getNote());

            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<Map<String, Object>> aabb() {
        return hazardousChemicalsRepository.aabb();
    }

    @Override
    public Map<String, String> checkInventory(Integer id, Float amount) {
        Map<String, String> map = new HashMap<>();
        HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.getById(id);
        if (hazardousChemicals.getUnit() == 1) {
            hazardousChemicals.setAmount(1000 * hazardousChemicals.getAmount());
            if (Objects.equals(hazardousChemicals.getAmount(), amount)) {
                map.put("result", "数量匹配");
            } else if (hazardousChemicals.getAmount() > amount) {
                map.put("result", "盘盈");
            } else {
                map.put("result", "盘亏");
            }
        } else {
            if (Objects.equals(hazardousChemicals.getAmount(), amount)) {
                map.put("result", "数量匹配");
            } else if (hazardousChemicals.getAmount() > amount) {
                map.put("result", "盘盈");
            } else {
                map.put("result", "盘亏");
            }
        }
        return map;
    }

    @Override
    public void updateInventory(Integer id, Float amount) {
        HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.getById(id);
        if (hazardousChemicals.getUnit() == 1) {
            hazardousChemicals.setAmount(amount / 1000f);
            hazardousChemicalsRepository.save(hazardousChemicals);
        } else {
            hazardousChemicals.setAmount(amount);
            hazardousChemicalsRepository.save(hazardousChemicals);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void panKu(int userId, List<Map<String, Object>> data) {
        for (Map<String, Object> map : data) {
            if (map.get("id") != null && map.get("actual") != "") {
                HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.getById(Convert.toInt(map.get("id")));

                HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.
                        findByNameAndType(hazardousChemicals.getName(), hazardousChemicals.getType());

                hazardousChemicalsTotal.setTotalNumber(
                        hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue() + Convert.toFloat(map.get("actual"))
                );

                hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);

                HazardousChemicalsChangeRecord hazardousChemicalsChangeRecord = new HazardousChemicalsChangeRecord();
                if (hazardousChemicals.isBiaoZhunWuZhi()) {
                    hazardousChemicalsChangeRecord.setBatchNumber(hazardousChemicals.getBatchNumber());
                    hazardousChemicalsChangeRecord.setExpirationDate(hazardousChemicals.getExpirationDate());
                    hazardousChemicalsChangeRecord.setMatrix(hazardousChemicals.getMatrix());
                    hazardousChemicalsChangeRecord.setNumber(hazardousChemicals.getNumber());
                    hazardousChemicalsChangeRecord.setIngredientData(hazardousChemicals.getIngredientData());
                }

                hazardousChemicalsChangeRecord.setUserId(userId);
                hazardousChemicalsChangeRecord.setHcId(hazardousChemicals.getId());
                hazardousChemicalsChangeRecord.setName(hazardousChemicals.getName());
                hazardousChemicalsChangeRecord.setAmount(hazardousChemicals.getAmount());
                hazardousChemicalsChangeRecord.setType(hazardousChemicals.getType());
                hazardousChemicalsChangeRecord.setState(HazardousChemicalsChangeRecord.STATE_PAN_KU);
                hazardousChemicalsChangeRecord.setOrderId(0);
                hazardousChemicalsChangeRecord.setDetailNumber(Convert.toFloat(map.get("actual")) - hazardousChemicals.getResidue());

                if (hazardousChemicals.getResidue() >= Convert.toFloat(map.get("actual"))){//实际量小于剩余量，类似领取行为
                    hazardousChemicalsChangeRecord.setLqNumber(hazardousChemicals.getResidue() - Convert.toFloat(map.get("actual")));
                    hazardousChemicalsChangeRecord.setUsedNumber(hazardousChemicals.getResidue() - Convert.toFloat(map.get("actual")));
                }else {
                    hazardousChemicalsChangeRecord.setGhNumber(Convert.toFloat(map.get("actual")) - hazardousChemicals.getResidue());//实际量大于剩余量，类似归还行为
                }
                hazardousChemicalsChangeRecord.setIsReturn(2);//非领取操作
                hazardousChemicalsChangeRecordRepository.save(hazardousChemicalsChangeRecord);

                hazardousChemicals.setResidue(Convert.toFloat(map.get("actual")));
                hazardousChemicalsRepository.save(hazardousChemicals);
            }
        }
    }

    @Override
    public List<HazardousChemicalsDto> getByType(Integer type) {
        List<HazardousChemicalsDto> data = hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.getByType(type));

        for (HazardousChemicalsDto dto : data) {
            dto.parseInfo();
        }
        return data;
    }

    @Override
    public List<HazardousChemicalsDto> distanceEquipmentList() {
        return hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.findDistanceEquipment());
    }

    @Override
    public HazardousChemicalsDto soloEquipment(Integer id) {
        return hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.findSoloEquipment(id));
    }

    @Override
    public List<HazardousChemicalsDto> distanceStandardSubstance() {
        return hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.findDistanceStandardSubstance());
    }

    @Override
    public List<HazardousChemicalsDto> distanceChemicalReagent() {
        return hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.findDistanceChemicalReagent());
    }


    private List<ProjectIdNameDto> getProjectName(HazardousChemicalsTotalDto hazardousChemicalsTotalDto) {
        List<Project> projectNameList = projectRepository.findByNameAndType(hazardousChemicalsTotalDto.getId(), hazardousChemicalsTotalDto.getType());
        List<ProjectIdNameDto> projectIdNameDtoList = new ArrayList<>();
        if (projectNameList != null) {
            for (Project p : projectNameList) {
                ProjectIdNameDto projectIdNameDto = new ProjectIdNameDto();
                projectIdNameDto.setName(p.getName());
                projectIdNameDto.setId(p.getId());
                projectIdNameDtoList.add(projectIdNameDto);
            }
            return projectIdNameDtoList;
        } else {
            return null;
        }
    }

    @Override
    public void burning(Integer[] ids) {
        for (Integer id : ids) {
            HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
            ValidationUtil.isNull(hazardousChemicals.getId(), "HazardousChemicals", "id", id);

            HazardousChemicalsChangeRecord hazardousChemicalsChangeRecord = new HazardousChemicalsChangeRecord();
            hazardousChemicalsChangeRecord.setHcId(hazardousChemicals.getId());
            hazardousChemicalsChangeRecord.setUserId(Convert.toInt(SecurityUtils.getCurrentUserId()));
            hazardousChemicalsChangeRecord.setName(hazardousChemicals.getName());
            if (hazardousChemicals.isQiCai()) {
                if ("1".equals(hazardousChemicals.getCategory()) || "2".equals(hazardousChemicals.getCategory())) {
                    hazardousChemicalsChangeRecord.setAmount(hazardousChemicals.getAmount());
                    hazardousChemicalsChangeRecord.setDetailNumber(hazardousChemicals.getAmount());
                } else {
                    hazardousChemicalsChangeRecord.setAmount(1f);
                    hazardousChemicalsChangeRecord.setDetailNumber(1f);
                }
            } else if (hazardousChemicals.isHuaXueShiJi()) {
                hazardousChemicalsChangeRecord.setAmount(hazardousChemicals.getAmount());
                hazardousChemicalsChangeRecord.setDetailNumber(hazardousChemicals.getInputResidue());
            } else {
                if (hazardousChemicals.getUnit() == 1) {
                    hazardousChemicalsChangeRecord.setDetailNumber(hazardousChemicals.getAmount());
                    hazardousChemicalsChangeRecord.setAmount(hazardousChemicals.getAmount());
                } else {
                    hazardousChemicalsChangeRecord.setDetailNumber(hazardousChemicals.getCapacity());
                    hazardousChemicalsChangeRecord.setAmount(hazardousChemicals.getAmount());
                }

            }
            hazardousChemicalsChangeRecord.setType(hazardousChemicals.getType());
            hazardousChemicalsChangeRecord.setState(HazardousChemicalsChangeRecord.STATE_SELL_INVENTORY);
            hazardousChemicalsChangeRecord.setAttenuation(hazardousChemicals.getAttenuation());
            hazardousChemicalsChangeRecord.setBatchNumber(hazardousChemicals.getBatchNumber());
            hazardousChemicalsChangeRecord.setExpirationDate(hazardousChemicals.getExpirationDate());
            hazardousChemicalsChangeRecord.setIngredientData(hazardousChemicals.getIngredientData());
            hazardousChemicalsChangeRecord.setMatrix(hazardousChemicals.getMatrix());
            hazardousChemicalsChangeRecord.setNumber(hazardousChemicals.getNumber());
            hazardousChemicalsChangeRecord.setFileUrl(hazardousChemicals.getFileUrl());
            hazardousChemicalsChangeRecordRepository.save(hazardousChemicalsChangeRecord);

            if (hazardousChemicals.isQiCai()) {
//                List<Integer> changeIds = hazardousChemicalsChangeRecordRepository.findByHcId(hazardousChemicals.getId());
//                for (Integer changeId : changeIds) {
//                    hazardousChemicalsChangeRecordRepository.deleteById(changeId);
//                }

                HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameAndType(hazardousChemicals.getName(), hazardousChemicals.getType());
                if (hazardousChemicals.getCountType() == 1) {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getAmount());
//                    hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getTotalNumber()-hazardousChemicals.getAmount());

                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                } else {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getAmount());
//                    hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getTotalNumber()-hazardousChemicals.getAmount());

                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                }
//                hazardousChemicalsRepository.deleteById(id);
            } else if (hazardousChemicals.isHuaXueShiJi()) {
//                List<Integer> changeIds = hazardousChemicalsChangeRecordRepository.findByHcId(hazardousChemicals.getId());
//                for (Integer changeId : changeIds) {
//                    hazardousChemicalsChangeRecordRepository.deleteById(changeId);
//                }
                HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameAndType(hazardousChemicals.getName(), hazardousChemicals.getType());
                if (hazardousChemicals.getCountType() == 1) {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                } else {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                }
//                hazardousChemicalsRepository.deleteById(id);
            } else {
//                List<Integer> changeIds = hazardousChemicalsChangeRecordRepository.findByHcId(hazardousChemicals.getId());
//                for (Integer changeId : changeIds) {
//                    hazardousChemicalsChangeRecordRepository.deleteById(changeId);
//                }
                HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameAndType(hazardousChemicals.getName(), hazardousChemicals.getType());
                if (hazardousChemicals.getCountType() == 1) {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                } else {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                }
//                hazardousChemicalsRepository.deleteById(id);
            }

            hazardousChemicals.setAmount(0f);
            hazardousChemicals.setResidue(0f);
            hazardousChemicalsRepository.save(hazardousChemicals);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void destroy(Integer[] ids) {
        for (Integer id : ids) {
            HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
            ValidationUtil.isNull(hazardousChemicals.getId(), "HazardousChemicals", "id", id);

            HazardousChemicalsChangeRecord hazardousChemicalsChangeRecord = new HazardousChemicalsChangeRecord();
            hazardousChemicalsChangeRecord.setHcId(hazardousChemicals.getId());
            hazardousChemicalsChangeRecord.setUserId(Convert.toInt(SecurityUtils.getCurrentUserId()));
            hazardousChemicalsChangeRecord.setName(hazardousChemicals.getName());
            hazardousChemicalsChangeRecord.setAmount(hazardousChemicals.getAmount());
            if (hazardousChemicals.isQiCai()) {
                if ("1".equals(hazardousChemicals.getCategory()) || "2".equals(hazardousChemicals.getCategory())) {
                    hazardousChemicalsChangeRecord.setAmount(hazardousChemicals.getAmount());
                    hazardousChemicalsChangeRecord.setDetailNumber(hazardousChemicals.getAmount());
                } else {
                    hazardousChemicalsChangeRecord.setAmount(1f);
                    hazardousChemicalsChangeRecord.setDetailNumber(1f);
                }
            } else if (hazardousChemicals.isHuaXueShiJi()) {
                hazardousChemicalsChangeRecord.setAmount(hazardousChemicals.getAmount());
                hazardousChemicalsChangeRecord.setDetailNumber(hazardousChemicals.getInputResidue());
            } else {
                if (hazardousChemicals.getUnit() == 1) {
                    hazardousChemicalsChangeRecord.setDetailNumber(hazardousChemicals.getAmount());
                    hazardousChemicalsChangeRecord.setAmount(hazardousChemicals.getAmount());
                } else {
                    hazardousChemicalsChangeRecord.setDetailNumber(hazardousChemicals.getCapacity());
                    hazardousChemicalsChangeRecord.setAmount(hazardousChemicals.getAmount());
                }

            }
            hazardousChemicalsChangeRecord.setType(hazardousChemicals.getType());
            hazardousChemicalsChangeRecord.setState(HazardousChemicalsChangeRecord.STATE_SELL_INVENTORY);
            hazardousChemicalsChangeRecord.setAttenuation(hazardousChemicals.getAttenuation());
            hazardousChemicalsChangeRecord.setBatchNumber(hazardousChemicals.getBatchNumber());
            hazardousChemicalsChangeRecord.setExpirationDate(hazardousChemicals.getExpirationDate());
            hazardousChemicalsChangeRecord.setIngredientData(hazardousChemicals.getIngredientData());
            hazardousChemicalsChangeRecord.setMatrix(hazardousChemicals.getMatrix());
            hazardousChemicalsChangeRecord.setNumber(hazardousChemicals.getNumber());
            hazardousChemicalsChangeRecord.setFileUrl(hazardousChemicals.getFileUrl());
            hazardousChemicalsChangeRecordRepository.save(hazardousChemicalsChangeRecord);

            if (hazardousChemicals.isQiCai()) {
                List<Integer> changeIds = hazardousChemicalsChangeRecordRepository.findByHcId(hazardousChemicals.getId());
                for (Integer changeId : changeIds) {
                    hazardousChemicalsChangeRecordRepository.deleteById(changeId);
                }

                HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameAndType(hazardousChemicals.getName(), hazardousChemicals.getType());
                if (hazardousChemicals.getCountType() == 1) {
                    if (hazardousChemicals.getResidue() > 0) {
                        hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
                    }

//                    hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getTotalNumber()-hazardousChemicals.getAmount());

                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                } else {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getAmount());
//                    hazardousChemicalsTotal.setGross(hazardousChemicalsTotal.getTotalNumber()-hazardousChemicals.getAmount());

                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                }
                hazardousChemicalsRepository.deleteById(id);
            } else if (hazardousChemicals.isHuaXueShiJi()) {
                List<Integer> changeIds = hazardousChemicalsChangeRecordRepository.findByHcId(hazardousChemicals.getId());
                for (Integer changeId : changeIds) {
                    hazardousChemicalsChangeRecordRepository.deleteById(changeId);
                }
                HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameAndType(hazardousChemicals.getName(), hazardousChemicals.getType());
                if (hazardousChemicals.getCountType() == 1) {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                } else {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                }
                hazardousChemicalsRepository.deleteById(id);
            } else {
                List<Integer> changeIds = hazardousChemicalsChangeRecordRepository.findByHcId(hazardousChemicals.getId());
                for (Integer changeId : changeIds) {
                    hazardousChemicalsChangeRecordRepository.deleteById(changeId);
                }
                HazardousChemicalsTotal hazardousChemicalsTotal = hazardousChemicalsTotalRepository.findByNameAndType(hazardousChemicals.getName(), hazardousChemicals.getType());
                if (hazardousChemicals.getCountType() == 1) {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                } else {
                    hazardousChemicalsTotal.setTotalNumber(hazardousChemicalsTotal.getTotalNumber() - hazardousChemicals.getResidue());
                    hazardousChemicalsTotalRepository.save(hazardousChemicalsTotal);
//                    if (hazardousChemicalsTotal.getTotalNumber() == 0) {
//                        hazardousChemicalsTotalRepository.deleteById(hazardousChemicalsTotal.getId());
//                    }
                }
                hazardousChemicalsRepository.deleteById(id);
            }
        }
    }

    private String generateNumber(Integer num) {
        StringBuffer msg = new StringBuffer("000000000000");
        String numString = String.valueOf(num);
        int start = 12 - numString.length();
        msg.replace(start, 12, numString);

        return msg.toString();
    }

}
